import React, { useState, useEffect } from 'react';
import { Modal, Form, Input, Select, Button, message } from 'antd';
import YzhTree from '@com/YzhTree'
import api from '@/api/apiList';
import {
    permissionCodes as pCodes
} from '@/routes/permission'
const { Option } = Select
const AddDepartDialog = (props) => {
    const [form] = Form.useForm();
    const [loading, setLoading] = useState(false)
    const [state, setState] = useState({
        dialogAddVisible: props.dialogAddVisible,
        erpOptions: [],
        initialValues: {
            deptName: props.deptName || undefined,
            pid: props.pid || undefined,
            deptErpCode: props.deptErpCode || undefined
        }
    })
    useEffect(() => {
        const getTreeData = async () => {
            try {
                let res = await api.common.departmentCombobox({},
                    props.id ? pCodes.dept.edit : pCodes.dept.add)
                setState({
                    erpOptions: res && res.result !== null ? res.result : [],
                    dialogAddVisible: props.dialogAddVisible
                })
            } catch (error) {
                console.log(error);
            }
        }
        getTreeData()
        form.setFieldsValue({
            deptName: props.deptName || undefined,
            pid: props.pid || undefined,
            deptErpCode: props.deptErpCode || undefined
        })
    }, [props, form])
    const onFinish = () => {
        form
            .validateFields()
            .then((values) => {
                setAddDialog()
                props.setAddDialog(values)
            })
            .catch((info) => {
                console.log('Validate Failed:', info);
            });
    }
    const setAddDialog = () => {
        setState({ ...state, dialogAddVisible: false })
    }
    // 获取erp数据
    const getErpData = async () => {
        setLoading(true)
        let res = await api.common.departmentSync({}, props.id ? pCodes.dept.edit : pCodes.dept.add)
        res && res.success && message.success('操作成功')
        setLoading(false)
    }
    const { dialogAddVisible, initialValues = {}, erpOptions } = state
    return <Modal
        maskClosable={false}
        centered
        title={`${props.id ? '编辑' : '新增'}部门`}
        width={500}
        wrapClassName="yzh-modal"
        visible={dialogAddVisible}
        onOk={onFinish}
        afterClose={() => {
            form.resetFields();
            props.setAddDialog()
        }}
        onCancel={setAddDialog}>
        <Form
            name="basic"
            form={form}
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 20 }}
            initialValues={initialValues}
            autoComplete="off"
        >
            <Form.Item
                label="部门名称"
                name="deptName"
                rules={[{ required: true, message: '请填写部门名称' }]}
            >
                <Input placeholder="请填写部门名称" maxLength={20} />
            </Form.Item>
            <Form.Item
                label="上级部门"
                name="pid"
                rules={[{ required: false, message: '请选择部门' }]}
            >
                {dialogAddVisible ? <YzhTree
                    onSelect={(val) => {
                        form.setFieldsValue({ pid: val })
                    }} value={props.pid} disabledId={props.id} select="true" /> : null}
            </Form.Item>
            <Form.Item
                label="erp部门"
                style={{ marginBottom: 0 }}
                rules={[{ required: false, message: '请选择erp部门' }]}
            >
                <Form.Item name="deptErpCode"
                    style={{ width: 240, float: 'left', marginBottom: 0 }}
                    rules={[{ required: false, message: '请选择erp部门' }]}
                >
                    {dialogAddVisible ? <Select
                        showSearch
                        placeholder="请选择erp部门"
                        value={props.deptErpCode || null}
                        optionFilterProp="label"
                        filterOption={(input, option) => {
                            return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0
                        }
                        }>
                        {
                            erpOptions.map(el => {
                                return <Option key={el.erpCode} value={el.erpCode} label={el.erpName}>{el.erpName}</Option>
                            })
                        }
                    </Select> : null}
                </Form.Item>
                <Button onClick={getErpData} loading={loading} style={{ float: 'right' }} size={'mini'}>获取erp数据</Button>
            </Form.Item>
        </Form>
    </Modal>
}

export default AddDepartDialog;